#include "loggingindialog.h"
#include "ui_loggingindialog.h"
#include"tcpmgr.h"

#include <QTimer>

LoggingInDialog::LoggingInDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::LoggingInDialog)
{
    ui->setupUi(this);

    _timer = new QTimer(this);
    connect(_timer, &QTimer::timeout, this, [this]{
        showTip(_LoginTip, true);
        _LoginTip += ".";
        if (_num % 4 == 0){
            _LoginTip = "正在登录";
        }
        _num++;
    });

    connect(this, &LoggingInDialog::sig_tcp_connect, TcpMgr::GetInstance().get(), &TcpMgr::slot_tcp_onnect);
    connect(TcpMgr::GetInstance().get(), &TcpMgr::sig_con_success, this, &LoggingInDialog::slot_tcp_con_finish);
    connect(TcpMgr::GetInstance().get(), &TcpMgr::sig_login_failed, this, [this](bool isLogIn){
        if (isLogIn){
            emit sig_switch_main(_user);
            showTip("聊天服务器登录成功", true);
            return;
        }
        _timer->stop();
        showTip("聊天服务器登录失败", false);
        return;
    });
}

LoggingInDialog::~LoggingInDialog()
{
    delete ui;
}

void LoggingInDialog::connectTcp(const ServerInfo &s)
{
    showTip(_LoginTip, true);
    _token = s.Token;
    _user = s.user;
    _timer->start(300); // 设置定时器间隔为 500 毫秒（0.5 秒）
    emit sig_tcp_connect(s);
}

void LoggingInDialog::setPixmap(const QPixmap &pixmap)
{
    ui->label->setPixmap(pixmap);
}

void LoggingInDialog::showTip(const QString &test, bool isOk)
{
    if(isOk){
        ui->Lingtip->setProperty("state", "normal");
        repolish(ui->Lingtip);
    }else{
        ui->Lingtip->setProperty("state", "err");
        repolish(ui->Lingtip);
    }
    ui->Lingtip->setText(test);
}

void LoggingInDialog::slot_tcp_con_finish(bool bsuccess)
{
    if (bsuccess){
        QJsonObject jsonObj;
        jsonObj["token"] =_token;
        QJsonDocument doc(jsonObj);
        //发送tcp请求给chat server
        emit TcpMgr::GetInstance()->sig_send_data(ReqId::ID_CHAT_LOGIN, doc.toJson(QJsonDocument::Compact));
    }else{
        _timer->stop();
        showTip("聊天服务器链接失败", false);
    }
}
